import { Inject, Injectable } from '@nestjs/common';
import { LogService } from '../log/log.service';

@Injectable()
export class WechatService {
  @Inject(LogService)
  private readonly logService: LogService;

  /**
   * Server酱推送到微信
   * @param title 标题（必填）
   * @param desp 内容（选填，支持Markdown）
   */
  async sendServerChan(title: string, desp?: string) {
    const SENDKEY = process.env.SERVER_CHAN_KEY;

    if (!SENDKEY) {
      this.logService.warn('未配置 SERVER_CHAN_KEY，跳过微信推送');
      return;
    }

    const url = `https://sctapi.ftqq.com/${SENDKEY}.send`;

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title,
          desp: desp || '', // 支持 Markdown 格式
        }),
      });

      const result = await response.json();

      if (result.code === 0) {
        this.logService.info(`微信推送成功: ${title}`);
      } else {
        this.logService.error(`微信推送失败: ${result.message}`);
      }

      return result;
    } catch (error) {
      this.logService.error('Server酱推送异常', error);
    }
  }
}
